const express = require('express')
const fs = require('fs')
const path = require('path')
const router = express.Router()

router.get('/', (req, res) => {
  const { fileName, chunkSize, chunkIndex } = req.query;

  const filePath = path.join(__dirname, 'uploads', fileName);

  console.log(filePath);

  // 检查文件是否存在
  if (!fs.existsSync(filePath)) {
      return res.status(404).json({ error: '文件不存在' });
  }

  // 获取文件大小
  const stats = fs.statSync(filePath);
  const fileSize = stats.size;

  console.log(stats)

  const start = parseInt(chunkIndex, 10) * parseInt(chunkSize, 10);
  let end = (parseInt(chunkIndex, 10) + 1) * parseInt(chunkSize, 10) - 1;

  // 处理边界情况，确保 end 不超过文件大小
  if (end >= fileSize) {
      end = fileSize - 1;
  }

  // 计算实际的分块大小
  const actualChunkSize = end - start + 1;

  // 设置响应头
  res.writeHead(206, {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': actualChunkSize,
      'Content-Type': 'application/octet-stream',
  });

  const readStream = fs.createReadStream(filePath, { start, end });
  readStream.pipe(res);
})

module.exports = router
